from apscheduler.schedulers.background import BackgroundScheduler
from application.config.TimedTaskConfig import TimedTaskConfig
from application.mapper.UserMapper import UserMapper
from application.util.EmailUtil import send_email
from datetime import datetime, timedelta
from threading import Thread
from application import app


class TimedTaskMiddleware:
    def __init__(self) -> None:
        self.scheduler: BackgroundScheduler = BackgroundScheduler()

    def birthday_task(self, advance_day: int) -> None:
        """
        生日提醒任务
        :param advance_day: 提前几天提醒
        :return:
        """
        # 创建一个Flask实例上下文，用于操作数据库
        with app.app_context():
            # 获取所有用户信息
            user_list: list = UserMapper.info_list()
        # 用户id和邮箱的映射
        user_dict: dict = {user.id: user.email for user in user_list}
        for user in user_list:
            # 交换邮箱（只有两个用户的时候有效）
            now_email: str = [user_email for user_id, user_email in user_dict.items() if user_id != user.id][0]
            # 生日提醒日期
            birthday_datetime: datetime = datetime.fromtimestamp(user.birthday) - timedelta(days=advance_day)
            # 添加定时任务（发送邮件）
            self.scheduler.add_job(send_email, "cron", month=birthday_datetime.month,
                                   day=birthday_datetime.day, hour=13, minute=14,
                                   args=[now_email, "对象生日提醒", f"还有{advance_day}天就是他/她的生日了，记得准备礼物哦~"])
        # 启动调度器
        self.scheduler.start()

    def start_all(self) -> None:
        """
        启动所有定时任务
        :return:
        """
        # 启动birthday_task线程
        Thread(target=self.birthday_task, args=(TimedTaskConfig.birthday_task_advance_day,)).start()

    def shutdown_all(self) -> None:
        """
        关闭所有定时任务
        :return:
        """
        self.scheduler.shutdown()
